/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pt.iasd.youthshelter.wizards.core.events.investiture;

import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.table.DefaultTableModel;
import org.openide.DialogDescriptor;
import org.openide.DialogDisplayer;
import org.openide.NotifyDescriptor;
import org.openide.WizardDescriptor;
import org.openide.util.Lookup;
import pt.iasd.youthshelter.datamodel.Investiture;
import pt.iasd.youthshelter.datamodel.service.InvestitureController;
import pt.iasd.youthshelter.wizards.core.WizardKeys;

/**
 *
 * @author Rui
 */
public class InvestitureTablePanel extends javax.swing.JPanel {
    private static final ResourceBundle bundle = java.util.ResourceBundle.getBundle("pt/iasd/youthshelter/wizards/core/Bundle");
    /* Logging object. */
    private Logger logger = Logger.getLogger(this.getClass().getName());
    
    private List<Investiture> distinctInvestitures = loadInvestitureTableData();
    
    private Set<Investiture> editedInvestitures = new HashSet<>();
    
    private Set<Investiture> removedInvestitures = new HashSet<>();
    
    private List<Investiture> completeInvestitures = loadCompleteInvestitureData();

    /**
     * Creates new form InvestitureTablePanel
     */
    public InvestitureTablePanel() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        TableScrollPane = new javax.swing.JScrollPane();
        InvestitureTable = new javax.swing.JTable();
        AddButton = new javax.swing.JButton();
        EditButton = new javax.swing.JButton();
        RemoveButton = new javax.swing.JButton();

        setPreferredSize(new java.awt.Dimension(700, 300));

        InvestitureTable.setModel(buildTableModel());
        InvestitureTable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                InvestitureTableMousePressed(evt);
            }
        });
        TableScrollPane.setViewportView(InvestitureTable);

        org.openide.awt.Mnemonics.setLocalizedText(AddButton, bundle.getString("Buttons.Add"));
        AddButton.setMaximumSize(new java.awt.Dimension(100, 23));
        AddButton.setMinimumSize(new java.awt.Dimension(100, 23));
        AddButton.setPreferredSize(new java.awt.Dimension(100, 23));
        AddButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                AddButtonActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(EditButton, bundle.getString("Buttons.Edit"));
        EditButton.setEnabled(false);
        EditButton.setMaximumSize(new java.awt.Dimension(100, 23));
        EditButton.setMinimumSize(new java.awt.Dimension(100, 23));
        EditButton.setPreferredSize(new java.awt.Dimension(100, 23));
        EditButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                EditButtonActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(RemoveButton, bundle.getString("Buttons.Remove"));
        RemoveButton.setEnabled(false);
        RemoveButton.setMaximumSize(new java.awt.Dimension(100, 23));
        RemoveButton.setMinimumSize(new java.awt.Dimension(100, 23));
        RemoveButton.setPreferredSize(new java.awt.Dimension(100, 23));
        RemoveButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                RemoveButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(TableScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 584, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(AddButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(EditButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(RemoveButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(TableScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(AddButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(EditButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(RemoveButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(208, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void AddButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AddButtonActionPerformed
        List<WizardDescriptor.Panel<WizardDescriptor>> panels = new ArrayList<>();
        panels.add(new AddInvestitureWizardPanel());
        WizardDescriptor wiz = new WizardDescriptor(new WizardDescriptor.ArrayIterator<>(panels));
        wiz.setTitleFormat(new MessageFormat("{0}"));
        wiz.setTitle(bundle.getString("Investiture.Title.Add"));
        wiz.putProperty(WizardKeys.PROP_LIST, distinctInvestitures);
        if (DialogDisplayer.getDefault().notify(wiz) == WizardDescriptor.FINISH_OPTION) {
            String place = (String)wiz.getProperty(WizardKeys.PROP_PLACE);
            Date date = (Date)wiz.getProperty(WizardKeys.PROP_DATE);
            List<Investiture> list = (List<Investiture>)wiz.getProperty(WizardKeys.PROP_INVESTITURE_LIST);
            if(list != null && !list.isEmpty()) {
                for(Investiture investiture : list) {
                    investiture.setPlace(place);
                    investiture.setEventDate(date);
                }
                distinctInvestitures.add(list.get(0));
                completeInvestitures.addAll(list);
            }
            setTable();
        }
    }//GEN-LAST:event_AddButtonActionPerformed

    private void EditButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EditButtonActionPerformed
        int selectedRow = InvestitureTable.getSelectedRow();
        List<WizardDescriptor.Panel<WizardDescriptor>> panels = new ArrayList<>();
        panels.add(new EditInvestitureWizardPanel());
        WizardDescriptor wiz = new WizardDescriptor(new WizardDescriptor.ArrayIterator<>(panels));
        wiz.setTitleFormat(new MessageFormat("{0}"));
        wiz.setTitle(bundle.getString("Investiture.Title.Edit"));
        Investiture investiture = distinctInvestitures.get(selectedRow);
        wiz.putProperty(WizardKeys.PROP_PLACE, investiture.getPlace());
        wiz.putProperty(WizardKeys.PROP_DATE, investiture.getEventDate());
        wiz.putProperty(WizardKeys.PROP_LIST, distinctInvestitures);
        if (DialogDisplayer.getDefault().notify(wiz) == WizardDescriptor.FINISH_OPTION) {
            String place = (String)wiz.getProperty(WizardKeys.PROP_PLACE);
            Date date = (Date)wiz.getProperty(WizardKeys.PROP_DATE);
            List<Investiture> list = (List<Investiture>)wiz.getProperty(WizardKeys.PROP_INVESTITURE_LIST);
            List<Investiture> editList = (List<Investiture>)wiz.getProperty(WizardKeys.PROP_EDIT_LIST);
            List<Investiture> removeList = (List<Investiture>)wiz.getProperty(WizardKeys.PROP_REMOVE_LIST);
            for(Investiture invest : list) {
                if(investiture.getId() == null) {
                    completeInvestitures.add(invest);
                }
            }
            removedInvestitures.addAll(removeList);
            editedInvestitures.addAll(editList);
            if(!place.equalsIgnoreCase(investiture.getPlace())
                    || !date.equals(investiture.getEventDate())) {
                for(Investiture invest : completeInvestitures) {
                    if(invest.getPlace().equalsIgnoreCase(investiture.getPlace())
                            && invest.getEventDate().equals(investiture.getEventDate())) {
                        invest.setPlace(place);
                        invest.setEventDate(date);
                        if(invest.getId() != null) {
                            editedInvestitures.add(invest);
                        }
                    }
                }
            }
            investiture.setPlace(place);
            investiture.setEventDate(date);
            setTable();
        }
    }//GEN-LAST:event_EditButtonActionPerformed

    private void RemoveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_RemoveButtonActionPerformed
        int selectedRow = InvestitureTable.getSelectedRow();
        SimpleDateFormat formatter = new SimpleDateFormat("dd-mm-yyyy");
        NotifyDescriptor dialog = new NotifyDescriptor(
            String.format(bundle.getString("Investiture.Confirmation.Remove"),
                distinctInvestitures.get(selectedRow).getPlace(),
                formatter.format(distinctInvestitures.get(selectedRow).getEventDate())),
            bundle.getString("Investiture.Title.Remove"), NotifyDescriptor.OK_CANCEL_OPTION,
            NotifyDescriptor.WARNING_MESSAGE, null, null);
        if(DialogDisplayer.getDefault().notify(dialog) == DialogDescriptor.OK_OPTION) {
            Investiture investiture = distinctInvestitures.get(selectedRow);
            for(Investiture invest : completeInvestitures) {
                if(invest.getId() != null && invest.getPlace().equalsIgnoreCase(investiture.getPlace())
                        && invest.getEventDate().equals(investiture.getEventDate())) {
                    removedInvestitures.add(invest);
                }
            }
            distinctInvestitures.remove(selectedRow);
            setTable();
        }
    }//GEN-LAST:event_RemoveButtonActionPerformed

    private void InvestitureTableMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_InvestitureTableMousePressed
        int selectedRow = InvestitureTable.getSelectedRow();
        if(selectedRow != -1) {
            EditButton.setEnabled(true);
            RemoveButton.setEnabled(true);
        } else {
            EditButton.setEnabled(false);
            RemoveButton.setEnabled(false);
        }
    }//GEN-LAST:event_InvestitureTableMousePressed

    public List<Investiture> getDistinctInvestitures() {
        return distinctInvestitures;
    }

    public Set<Investiture> getEditedInvestitures() {
        return editedInvestitures;
    }

    public Set<Investiture> getRemovedInvestitures() {
        return removedInvestitures;
    }

    public List<Investiture> getCompleteInvestitures() {
        return completeInvestitures;
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton AddButton;
    private javax.swing.JButton EditButton;
    private javax.swing.JTable InvestitureTable;
    private javax.swing.JButton RemoveButton;
    private javax.swing.JScrollPane TableScrollPane;
    // End of variables declaration//GEN-END:variables

    // <editor-fold defaultstate="collapsed" desc="Table Data Code">
    private List<Investiture> loadCompleteInvestitureData() {
        InvestitureController controller = Lookup.getDefault().lookup(InvestitureController.class);
        if(controller != null) {
            try{
                return controller.findInvestitureEntities();
            } catch(Exception ex) {
                logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
            }
        }
        return null;
    }
    
    private List<Investiture> loadInvestitureTableData() {
        InvestitureController controller = Lookup.getDefault().lookup(InvestitureController.class);
        if(controller != null) {
            try{
                return controller.findDistinctInvestitureEntities();
            } catch(Exception ex) {
                logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
            }
        }
        return null;
    }
    
    private DefaultTableModel buildTableModel(){
        Object[][] data;
        String[] headers = new String[]{
            bundle.getString("TableHeaders.Place"),
            bundle.getString("TableHeaders.Date")};
        if(distinctInvestitures == null || distinctInvestitures.isEmpty()) {
            data = new Object[][]{};
        } else {
            data = new Object[distinctInvestitures.size()][Investiture.class.getDeclaredFields().length - 7];
            int i = 0;
            for(Investiture investiture : distinctInvestitures) {
                data[i][0] = investiture.getPlace();
                data[i][1] = investiture.getEventDate();
                ++i;
            }
        }
        DefaultTableModel tablemodel = new DefaultTableModel(data, headers){
            Class[] types = new Class[]{java.lang.String.class, java.util.Date.class};
            boolean[] canEdit = new boolean[]{false, false};

            @Override
            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            @Override
            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        };
        return tablemodel;
    }
    
    private void setTable() {
        InvestitureTable.setModel(buildTableModel());
        EditButton.setEnabled(false);
        RemoveButton.setEnabled(false);
    }// </editor-fold>
}
